package red.stu.wechat.factory.robot;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import com.alibaba.fastjson.JSON;

import me.xuxiaoxiao.chatapi.wechat.entity.message.WXMessage;
import me.xuxiaoxiao.xtools.common.http.XHttpTools;
import me.xuxiaoxiao.xtools.common.http.XOption;
import me.xuxiaoxiao.xtools.common.http.XRequest;

/**
 * 微信机器人回调
 * @author yihrmc
 *
 */
public class WeChatRoobotCallback {
	
	private static final XOption HTTP_OPTION_DEFAULT = XHttpTools.DEFAULT_OPTION;
	
	private String signId;
	private String callbackUrl;
	private String charset;
	private WeChatRobot robot;

	public WeChatRoobotCallback(String signId, String callbackUrl, String charset) {
		this.signId = signId;
		this.callbackUrl = callbackUrl;
		this.charset = charset;
	}

	public void onInit(WeChatRobot robot) {
		this.robot = robot;
	}

	/**
	 * 获取到用户登录的二维码
	 * 
	 * @param rid
	 * @param qrCode
	 *            用户登录二维码的url
	 */
	public void onQRCode(String rid, String qrCode) {
		request(XRequest.POST(callbackUrl + "/onQRCode")
				.content("signId", signId)
				.content("rid", rid)
				.content("qrCode", qrCode));
	}

	/**
	 * 获取用户头像，base64编码
	 * 
	 * @param rid
	 * @param base64Avatar
	 *            base64编码的用户头像
	 */
	public void onAvatar(String rid, String base64Avatar) {
		request(XRequest.POST(callbackUrl + "/onAvatar")
				.content("signId", signId)
				.content("rid", rid)
				.content("base64Avatar", base64Avatar));
	}

	/**
	 * 模拟网页微信客户端异常退出
	 * 
	 * @param rid
	 * @param reason
	 *            错误原因
	 */
	public void onFailure(String rid, String reason) {
		request(XRequest.POST(callbackUrl + "/onFailure")
				.content("signId", signId)
				.content("rid", rid)
				.content("reason", reason));
	}

	/**
	 * 用户登录并初始化成功
	 * 
	 * @param rid
	 */
	public void onLogin(String rid) {
		for (String key : robot.client.userFriends().keySet()) {
			System.out.println("id: " + robot.client.userFriends().get(key).id);
		}
		request(XRequest.POST(callbackUrl + "/onLogin")
				.content("signId", signId)
				.content("rid", rid));
	}

	/**
	 * 用户获取到消息
	 * 
	 * @param rid
	 * @param message
	 *            用户获取到的消息
	 */
	public void onMessage(String rid, WXMessage message) {
		System.out.println(JSON.toJSONString(message));
		try {
			request(XRequest.POST(callbackUrl + "/onMessage")
					.content("signId", signId)
					.content("rid", rid)
					.content("message", URLDecoder.decode(JSON.toJSONString(message), "UTF-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 模拟网页微信客户端正常退出
	 * 
	 * @param rid
	 */
	public void onLogout(String rid) {
		request(XRequest.POST(callbackUrl + "/onLogout")
				.content("signId", signId)
				.content("rid", rid));
		robot.client.shutdown();
	}
	
	/**
	 * 异常回调
	 * @param rid
	 * @param exceptionClasName 异常类名
	 * @param errorInfo 错误信息
	 */
	public void onException(String rid, String exceptionClassName, String message) {
		requestGException(XRequest.POST(callbackUrl + "/onException")
				.content("signId", signId)
				.content("rid", rid)
				.content("className", exceptionClassName)
				.content("message", message));
	}
	
	/**
	 * 发起请求
	 * @param request
	 * @return
	 */
	private String request(XRequest request) {
		try {
			return XHttpTools.http(HTTP_OPTION_DEFAULT, request).string(charset);
		} catch (Exception e) {
			onException(robot.rid, e.getClass().toString(), e.getMessage());
		}
		return null;
	}
	
	/**
	 * 发起请求 - 忽略异常
	 * @param request
	 * @return
	 */
	private String requestGException(XRequest request) {
		try {
			return XHttpTools.http(HTTP_OPTION_DEFAULT, request).string(charset);
		} catch (Exception e) {}
		return null;
	}

}